package vn.njai.thousand_english_word.Utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.AssetManager;
import android.graphics.Color;
import android.os.Handler;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import com.google.gson.Gson;
import vn.njai.thousand_english_word.Entities.*;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Random;

/**
 * Created by VUONG on 12/25/2014.
 */
public class DataManager {
    private String TAG = "DataManager";
    public SharedPreferences mPrefs;
    public Context mContext;
    public LoadingListener mListener;
    public Gson gson;
    public ArrayList<Integer> mListColor;
    public Learning mLearning;
    public NeedLearn mNeedLearn;
    public HistoryData mHistoryData;
    public int mWordCount = 1000;
    public int mVolume;

    public DetailData mDetailData;

    private static DataManager instance;

    public static DataManager getInstance(){
        if(instance == null){
            instance = new DataManager();
        }
        return instance;
    }

    public void init(){
        gson = new Gson();
        mLearning = new Learning();
        mDetailData = new DetailData();
        mHistoryData = new HistoryData();
        mPrefs = ((ActionBarActivity)mContext).getPreferences(Context.MODE_PRIVATE);
        mListColor = new ArrayList<Integer>();
        mListColor.add(Color.rgb(77, 77, 77));
        mListColor.add(Color.rgb(47,177,171));
        mListColor.add(Color.rgb(124,150,59));
        mListColor.add(Color.rgb(241,106,112));
        mListColor.add(Color.rgb(193,106,20));
    }

    public void getDetailData(){
        DataManager.getInstance().mDetailData = new DetailData();
        for(int i = 0;i<DataManager.getInstance().mWordCount;i++){
            HistoryNodeItem historyNodeItem = new HistoryNodeItem(DataManager.getInstance().getNodeAt(i+1));
            switch (historyNodeItem.mRemember){
                case 0:
                    DataManager.getInstance().mDetailData.mListNever.add(historyNodeItem);
                    break;
                case 1:
                    DataManager.getInstance().mDetailData.mListOneTime.add(historyNodeItem);
                    break;
                case 2:
                    DataManager.getInstance().mDetailData.mListTwoTime.add(historyNodeItem);
                    break;
                case 3:
                    DataManager.getInstance().mDetailData.mListLeaned.add(historyNodeItem);
                    break;
            }
        }
        mListener.onLoadDetailComplete();
    }

    public boolean isLoadFromFile(){
        if(mPrefs.getString("IsLoadFile", "").equals("true"))
            return true;
        return false;
    }

    public void loadLearningList(){
        String json =  mPrefs.getString("LearningList","");
        mLearning = gson.fromJson(json, Learning.class);
    }

    public int loadVolume(){
        int volume =  mPrefs.getInt("Volume", 50);
        mVolume = volume;
        return volume;
    }

    public void saveVolume(final int volume){
        Handler handler = new Handler();
        handler.post(new Runnable() {
            @Override
            public void run() {
                SharedPreferences.Editor prefsEditor = mPrefs.edit();
                prefsEditor.putInt("Volume",volume);
                prefsEditor.commit();
            }
        });

    }

    public void loadHistoryList(){
        String json =  mPrefs.getString("HistoryList","");
        mHistoryData = gson.fromJson(json, HistoryData.class);
    }

    public void saveHistoryList(){
        Handler handler = new Handler();
        handler.post(new Runnable() {
            @Override
            public void run() {
                SharedPreferences.Editor prefsEditor = mPrefs.edit();
                String json = gson.toJson(mHistoryData);
                prefsEditor.putString("HistoryList", json);
                prefsEditor.commit();
                Log.e(TAG,"saveHistoryList");
            }
        });

    }

    public void loadNeedLearnList(){
        String json =  mPrefs.getString("NeedLearnList","");
        mNeedLearn = gson.fromJson(json, NeedLearn.class);
    }

    public void saveLearningList(){
        Handler handler = new Handler();
        handler.post(new Runnable() {
            @Override
            public void run() {
                SharedPreferences.Editor prefsEditor = mPrefs.edit();
                String json = gson.toJson(mLearning);
                prefsEditor.putString("LearningList", json);
                prefsEditor.commit();
                Log.e(TAG,"saveLearningList");
            }
        });

    }

    public void saveNeedLearnList(){
        Handler handler = new Handler();
        handler.post(new Runnable() {
            @Override
            public void run() {
                SharedPreferences.Editor prefsEditor = mPrefs.edit();
                String json = gson.toJson(mNeedLearn);
                prefsEditor.putString("NeedLearnList", json);
                prefsEditor.commit();
                Log.e(TAG,"saveNeedLearnList");
            }
        });

    }
//
//    public void getRandomListNode(){
//        while (mLearning.mLearningList.size()<5){
//            Random random = new Random();
//            int newID = random.nextInt(mNeedLearnList.mNeedLearnList.size())+1;
//            boolean isDup = false;
//            for(int i = 0;i<mLearning.mLearningList.size();i++){
//                if(newID == mLearning.mLearningList.get(i).mRank || mLearning.mLearningList.get(i).mRemember == 3 ){
//                    isDup = true;
//                }
//            }
//            if(isDup == false) {
//                NodeItem nodeItem = getNodeAt(newID - 1);
//                nodeItem.mColor = mListColor.get(mLearning.mLearningList.size());
//                mLearning.mLearningList.add(mLearning.mLearningList.size(), nodeItem);
//            }
//        }
//        saveLearningList();
//    }

    public NodeItem getRandomNode(){
        if(mNeedLearn.mNeedLearnList.size()<=0)
            return null;
        Random random = new Random();
        int newID = random.nextInt(mNeedLearn.mNeedLearnList.size());
        NodeItem nodeItem =getNodeAt(mNeedLearn.mNeedLearnList.get(newID));
        nodeItem.mColor = mListColor.get(mLearning.mLearningList.size());
        mNeedLearn.mNeedLearnList.remove(newID);
        return nodeItem;
    }

    public NodeItem getRandomNode(int oldColor){
        NodeItem nodeItem = this.getRandomNode();
        if(nodeItem != null)
            nodeItem.mColor = oldColor;
        return nodeItem;
    }

    public void setListener(LoadingListener listener){
        mListener = listener;
    }

    public NodeItem getNodeAt(int rank){
        String json =  mPrefs.getString("Word_" + rank, "");
        NodeItem obj = gson.fromJson(json, NodeItem.class);
        return obj;
    }

    public void setWordAt(NodeItem nodeItem){
        SharedPreferences.Editor prefsEditor = mPrefs.edit();
        String json = gson.toJson(nodeItem);
        prefsEditor.putString("Word_"+nodeItem.mRank, json);
        prefsEditor.commit();
    }

    public void loadDataFromFile(){
        SharedPreferences.Editor prefsEditor = mPrefs.edit();
        DataManager.getInstance().mLearning = null;
        DataManager.getInstance().mHistoryData = null;
        DataManager.getInstance().mNeedLearn = null;

        String json = gson.toJson(mLearning);
        prefsEditor.putString("LearningList", json);
        prefsEditor.commit();
        json = gson.toJson(mLearning);
        prefsEditor.putString("HistoryList", json);
        prefsEditor.commit();
        json = gson.toJson(mLearning);
        prefsEditor.putString("NeedLearnList", json);
        prefsEditor.commit();
        readFile();
        prefsEditor.putString("IsLoadFile", "true");
        prefsEditor.commit();
    }

    public void readFile(){
        final AssetManager am = mContext.getAssets();
        ArrayList<String> buf = new ArrayList<String>();
        try {
            InputStream is = am.open("dictionary_"+mWordCount+".txt");
            BufferedReader in =
                    new BufferedReader(new InputStreamReader(is, "UTF-8"));
            String str;

            while ((str = in.readLine()) != null) {
                buf.add(str);
            }

            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        NeedLearn needLearn = new NeedLearn();
        SharedPreferences.Editor prefsEditor = mPrefs.edit();
        Gson gson = new Gson();
        for (int i = 0; i < buf.size(); i++) {
            NodeItem nodeItem = new NodeItem();
            String[] separated = buf.get(i).split(";");
            if(separated.length >= 5) {
                String rank = separated[0];
                try {
                    nodeItem.mRank = Integer.parseInt(rank);
                } catch (NumberFormatException n) {

                }
                nodeItem.mWord = separated[1];
                nodeItem.mType = separated[3];
                nodeItem.mPhonetic = separated[2];
                nodeItem.mMeans = separated[4];
                mListener.onProgress(i);
                String json = gson.toJson(nodeItem);
                prefsEditor.putString("Word_"+nodeItem.mRank, json);
                needLearn.mNeedLearnList.add(nodeItem.mRank);
            }
        }
        prefsEditor.commit();
        String json1 = gson.toJson(needLearn);
        prefsEditor.putString("NeedLearnList", json1);
        prefsEditor.commit();
    }

    public interface LoadingListener{
        public void onProgress(int progress);
        public void onLoadDetailComplete();
    }
}
